<template>
  <div class="login_container">
    <div class="logo_box">
      <!-- <img src="../../assets/images/login/logo.png" alt=""> -->      
    </div>

    <div v-if="loginFlag === '1'" class="login_main">
      <div class="system_title">{{ systemTitle }}</div>
      <el-form :model="loginInfo" :rules="rules" ref="loginFormRef" class="login_form">
        <el-form-item prop="loginName">
          <el-input v-model.trim="loginInfo.loginName" :prefix-icon="User" placeholder="请输入账号" @keyup.enter="handleSubmit"
            maxlength="16" class="form_input">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model.trim="loginInfo.password" :prefix-icon="Lock" placeholder="请输入密码" @keyup.enter="handleSubmit"
            maxlength="12" class="form_input" type="password" show-password>
          </el-input>
        </el-form-item>

        <p class="login_tip">忘记密码？</p>
        <el-button type="primary" class="login_btn" :loading="loading"
          @click="handleSubmit(loginFormRef)">登录</el-button>

      </el-form>
    </div>
    <div v-if="loginFlag === '2'" class="login_main">
      <div class="system_title">{{ systemTitle }}</div>
      <el-form :model="passInfo" :rules="passRules" ref="passFormRef" class="login_form" inline-message>
        <el-form-item label="旧密码：" prop="oldPassword">
          <el-input type="password" v-model.trim="passInfo.oldPassword" show-password maxlength="12" placeholder="请输入旧密码"/>
        </el-form-item>
        <el-popover
          placement="top"
          trigger="hover"
          width = "200"
          :content="msgStr">
          <template #reference>
            <el-form-item label="新密码：" prop="password">
              <el-input type="password" v-model.trim="passInfo.password" show-password  placeholder="请输入新密码" />
            </el-form-item>
          </template>
        </el-popover>
        <el-form-item label="确认密码：" prop="vPassword">
          <el-input type="password" v-model.trim="passInfo.vPassword" show-password  placeholder="请输入新密码" />
        </el-form-item>
        <p style="color: brown;">密码过期，请修改！</p>
        <el-button type="primary" class="login_btn" @click="changePass">修改密码</el-button>

      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { User, Lock } from "@element-plus/icons-vue";



// 加载动画
const loading = ref(false);
const loginFlag = ref('1');//登录标记，1:登录页面, 2:修改密码

// 系统标题
const systemTitle = ref(import.meta.env.VITE_APP_TITLE);

// 用户信息相关
const loginInfo = reactive({
  loginName: "",
  password: "",
});

// 表单校验
const rules = {
  loginName: [
    { required: true, message: "请输入账号", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" }
  ],
};


/* -----------------登录相关--------------------------- */
//#region
import { login,getTokenUser } from "@/request/apis/login";
import { UserState } from "@store/types";
import useUserStore from "@store/modules/user";
import useDictStore from "@store/modules/dict";
import CryptoJS from 'crypto-js'
// // 路由相关
const router = useRouter(); // 相当于vue2中的this.$router
// 用户store
const userStore = useUserStore();
//字典store
const dictStore = useDictStore()
const loginFormRef = ref<FormInstance>();
function handleSubmit(formEl: FormInstance) {
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      let passMd5 = CryptoJS.MD5(loginInfo.password + loginInfo.loginName).toString();
      const loginData = {
        loginName:loginInfo.loginName,
        password:passMd5
      }
      login(loginData).then((data: any) => {
        if(data.passExpired === '0'){
            userStore.saveToken(data.accessToken,data.refreshToken);
            getTokenUser().then((data:any) =>{
              const userInfo = {
                id: data.id,
                avatar: data.avatar,
                name: data.uname, //用户名
                loginName: data.loginName, //用户登录账号
                orgId: data.deptid,
                permissions: data.permissions, //权限
              };
              userStore.saveUser(userInfo as UserState);          
              userStore.saveMenus(data.menuList, "pid", "id");
              ElMessage.success("登录成功！");
              router.replace({ name: "home" });
            })
            //获取数据字典
            dictStore.getInitDicDatas()
          }else{
            //密码过期去修改密码
            loginFlag.value = '2';//修改密码模式
            token.value = data.accessToken;            
            loading.value = false;
          }
      })
        .catch((err) => {
          loading.value = false;
        });
    }
  });
}
//#endregion

/********   修改密码相关 ******/
//#region
import { changeValidPassword } from "@/request/apis/system/userProfile";
import { getParameterByKey } from "@/request/apis/system/parameter";
import { parameterEnum } from '@/utils/staticData'
const passInfo = ref({})
const passFormRef = ref<FormInstance>();
const token = ref('')

//自定义校验函数
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入确认密码'))
  } else if (value !== passInfo.value.password) {
    callback(new Error("两次密码不一样"))
  } else {
    callback()
  }
}

//自定义校验函数
const ruleStr = ref('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[^]{8,12}$')
const msgStr = ref('8-12个字符,至少1个大写字母,1个小写字母和1个数字')
const validatePass = (rule, value, callback) => {
  const r = ruleStr.value
  const regex = new RegExp(r); 
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (!regex.test(value)) {
    callback(new Error('不符合密码规则'))
  } else {
    callback()
  }
}
// 表单校验规则
const passRules = reactive<FormRules>({
  oldPassword: [{ required: true, message: "不能为空", trigger: "blur" }],
  password: [
    { required: true, message: "不能为空", trigger: "blur" },
    { validator: validatePass, trigger: "blur" }
  ],
  vPassword: [
    { required: true, message: "不能为空", trigger: "change" },
    { validator: validatePass2, trigger: 'blur' }
  ],
})

//修改密码
function changePass() {
  passFormRef.value.validate((valid) => {
    if (valid) {
      let params = {
        oldPassword: CryptoJS.MD5(passInfo.value.oldPassword + userStore.userInfo.loginName).toString(),
        password: CryptoJS.MD5(passInfo.value.password + userStore.userInfo.loginName).toString()
      }
      changeValidPassword(params,token.value).then((res: any) => {
        ElMessage.success("操作成功")
        loginFlag.value = '1';//登录模式
        loginInfo.password = '';
      })
    }
  });
}

onMounted(()=>{
  getParameterByKey(parameterEnum['密码强度规则'])
  .then((data)=>{
    ruleStr.value = data.pvalue
    msgStr.value = data.remark
  })
})
//#endregion
</script>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: url(@images/login/loginBg.png) no-repeat;
  background-size: 100% 100%;

  .logo_box {
    position: absolute;
    left: 50%;
    top: 23%;
    width: vw(213);
    transform: translate(-50%, -50%);

    img {
      width: 100%;
    }
  }

  .login_main {
    width: vw(545);
    height: vh(470);
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    background: rgba(255, 255, 255, 0.8);
    box-shadow: 10px 10px 20px 10px #003880;
    border-radius: vw(15);

    .system_title {
      margin-top: vh(40);
      height: vh(45);
      line-height: vh(45);
      text-align: center;
      font-size: vw(24);
      font-weight: 600;
      color: #303133;
    }

    .login_form {
      position: relative;
      width: vw(380);
      height: vh(319);
      margin: vh(26) vw(82.5) vh(70);

      ::v-deep .el-form-item {
        margin-bottom: vh(30)
      }

      ::v-deep .el-form-item__error {
        height: vh(30);
        line-height: vh(30);
        left: vw(84);
      }

      .form_input {
        height: vh(56);

        ::v-deep .el-input__wrapper {
          border-radius: 0;
          // background: #fff;
        }

        ::v-deep .el-input__inner {
          // font-family: Adobe Heiti Std;
          height: 100%;
          padding-left: vw(20);
          font-size: vw(16);

          &::placeholder {
            color: #AAB3BD;
          }
        }

        ::v-deep .el-input__prefix {
          display: flex;
          justify-content: center;
          width: vw(53);
          height: vh(30);
          font-size: vw(24);
          border-right: vw(1) solid #AAB3BD;
        }
      }

      .login_tip {
        margin-top: 5px;
        font-size: vw(14);
        font-weight: 600;
        color: #003879;
        cursor: pointer;
      }

      .login_btn {
        position: absolute;
        bottom: 0;
        width: 100%;
        height: vh(53);
        font-size: vw(16);
      }
    }
  }
}
</style>